# tools/file_tool.py
import os

def read_file(file_path: str, encoding: str = "utf-8") -> str:
    try:
        with open(file_path, "r", encoding=encoding) as f:
            return f.read()
    except UnicodeDecodeError:
        logging.error("文件编码错误，请检查文件编码是否为 UTF-8")
        return ""
    except FileNotFoundError:
        logging.error("文件不存在")
        return ""

def write_file(file_path: str, content: str, encoding: str = "utf-8") -> None:
    with open(file_path, "w", encoding=encoding) as f:
        f.write(content)

def run():
    print("\n欢迎使用文件操作工具")
    print("1. 读取文件")
    print("2. 写入文件")
    choice = input("请选择操作（1 或 2）：")
    if choice == "1":
        file_path = input("请输入文件路径：")
        content = read_file(file_path)
        if content:
            print(f"文件内容：\n{content}")
    elif choice == "2":
        file_path = input("请输入文件路径：")
        content = input("请输入要写入的内容：")
        write_file(file_path, content)
        print("文件写入成功！")
    else:
        print("无效选项！")